﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Office.Interop.Excel;
using NLog;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wittur.GenereateKongCoCPDF.Core.Common;
using Wittur.GenereateKongCoCPDF.Core.Services;

namespace Wittur.GenereateKongCoCPDF.Core
{
    [DisallowConcurrentExecution]
    public class GenerateKongCoCPdfJob : IJob
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();
        private readonly IUserService _service;
        public GenerateKongCoCPdfJob(IUserService service)
        {
            this._service = service;
        }
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                logger.Info("任务开始");
                var dto = _service.GetConsulting();
                GenerateA4Pdf();
                logger.Info("结束任务");
            }
            catch (Exception ex)
            {
                logger.Error($"发生错误：{ex.Message}");
            }
            
        }
        /// <summary>
        /// 创建输出目录
        /// </summary>
        /// <returns></returns>
        private string GenerOutPutDir()
        {
            var outPutPath = ConfigHelper.Instance.GetString("Path", "PdfGenDir");
            return FileLogger.CreateFolderByDateAndOutPutPath(outPutPath);
        }
        private void GenerateA4Pdf()
        {
            var outPutPath = GenerOutPutDir();
            var ladderNo = "SO"; // 1 梯号
            var bjName_Source = "电梯层门锁装置";
            var bjName = ConfigHelper.Instance.GetString("ComponentName", bjName_Source); // 部件名称
            var gysName = "苏州威特"; // 供货方名称
            // 文档名：梯号_部件名称(参考左图列表)_供货方名称
            var fileName = $@"{ladderNo}_{bjName}_{gysName}.pdf"; // 
            var templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates", "合格证模板.xlsx");
            // 填充合格证 明细数据
            var saveTempPath = FillContent(templatePath);
            if (!string.IsNullOrEmpty(saveTempPath))
                //ExcelHepler.ConvertExcelToPdf(saveTempPath, Path.Combine(outPutPath, fileName));
                ExcelHepler.ConvertExcelToPdfByClosedXML(saveTempPath, Path.Combine(outPutPath, fileName));
        }

        private string FillContent(string templatePath)
        {
            var tempPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temp");
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            string fileName = $"KongCoC_Temp_{CommonHelper.GenerateShortId()}.xlsx";
            var savePath = Path.Combine(tempPath, fileName);


            // 打开文件流读取 Excel 文件
            using (FileStream fs = new FileStream(templatePath, FileMode.Open, FileAccess.ReadWrite))
            {
                XSSFWorkbook workbook = new XSSFWorkbook(fs);
                ISheet sheet = workbook.GetSheetAt(0);
                // 填充单元格数据
                FillCell(sheet, 23, 6, "Augusta-AMD 厅门门锁"); // 产品名称
                FillCell(sheet, 24, 6, "型号1"); // 产品型号
                FillCell(sheet, 25, 6, "批次号"); // 制造批次号
                FillCell(sheet, 26, 6, "合同号"); // 合同号
                FillCell(sheet, 27, 6, "2025-03-17"); // 校验日期

                // 保存修改后的 Excel 文件 FileShare.Read允许共享
                using (FileStream outputStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    workbook.Write(outputStream);
                }
                workbook.Close();
                return savePath;
            }

        }

        private void ConvertExcelStreamToPdf(FileStream excelStream, string pdfFilePath)
        {
            Microsoft.Office.Interop.Excel.Application excelApp = null;
            Workbook workbook = null;

            try
            {
                // 创建 Excel 应用程序实例
                excelApp = new Microsoft.Office.Interop.Excel.Application();
                excelApp.Visible = false; // 不显示 Excel 界面

                // 打开 Excel 文件
                // 通过文件流打开 Workbook
                workbook = excelApp.Workbooks.Open(excelStream.Name);
                logger.Info("打开文件正常");

                // 将 Excel 文件另存为 PDF
                workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfFilePath);
                Console.WriteLine("转换成功！");
            }
            catch (Exception ex)
            {
                logger.Error($"转换失败: {ex.Message}");
                Console.WriteLine($"转换失败: {ex.Message}");
            }
            finally
            {
                // 关闭工作簿和 Excel 应用程序
                if (workbook != null)
                {
                    workbook.Close(false);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                }

                if (excelApp != null)
                {
                    excelApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                }
            }
        }

        /// <summary>
        /// 填充单元格
        /// </summary>
        private void FillCell(ISheet sheet, int rowIndex, int cellIndex, string value)
        {
            IRow row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
            ICell cell = row.GetCell(cellIndex) ?? row.CreateCell(cellIndex);
            cell.SetCellValue(value);
        }
    }
}
